﻿using CommonLib.Attr;
using CommonLib.Base;
using CommonLib.CodeEntity;
using CommonLib.Util;

namespace Oracle.Lexer;

[Order(3)]
public class CaseLexer : BaseLexer
{
    public override bool Check()
        => Txt.StartsWith("CASE ");

    protected override BaseCodeEntity Run()
    {
        var entity = new CaseCodeEntity();
        var txt = Txt[4..].Trim();
        if (!txt.StartsWith("WHEN"))
        {
            var head = txt[..txt.IndexOf(" WHEN")].Trim();
            entity.Head = SqlFactory.Create(head).Execute();
            txt = txt.Replace(head, "").Trim();
        }
        var sub = new List<string>();
        while (string.IsNullOrEmpty(txt))
        {
            if (txt.Contains(" WHEN"))
            {
                var temp = txt;
                var item = temp[..temp.IndexOf(" WHEN")].Trim();
                while (!item.IsFull())
                {
                    temp = temp.Replace(item, "").Trim();
                    item = $"{item} {temp[..temp.IndexOf(" WHEN")].Trim()}";
                }
                sub.Add(temp);
                txt = txt.Replace(item, "").Trim();
            }
            else if (txt.Contains(" ELSE"))
            {
                var temp = txt;
                var item = temp[..temp.IndexOf(" ELSE")].Trim();
                while (!item.IsFull())
                {
                    temp = temp.Replace(item, "").Trim();
                    item = $"{item} {temp[..temp.IndexOf(" ELSE")].Trim()}";
                }
                sub.Add(temp);
                txt = txt.Replace(item, "").Trim();
            }
            else if (txt.StartsWith("ELSE"))
            {
                txt = txt[4..^3].Trim();
                entity.ElseBody = SqlFactory.Create(txt).Execute();
                break;
            }
        }

        sub.ForEach(s =>
        {
            entity.WhenList.Add(SqlFactory.Create(s).Execute());
        });
        return entity;
    }
}
